package com.yzl.frelink.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Commander {
    public static String getFretishFromJson(String filePath) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("node", "./js/index.js", "-r", filePath);
        Process process = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append("STDERR: ").append(line).append("\n");
        }
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new Exception("Command failed with exit code " + exitCode + "\n" + sb.toString());
        }
        reader.close();
        if (!sb.isEmpty()) {
            System.out.println(sb.toString());
        }
        return sb.toString();
    }

    public static String generateSLX(String filePath) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("matlab", "-nosplash", "-nodesktop", "-nodisplay", "-batch", "run(\'" + filePath + "\')");
        Process process = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append("STDERR: ").append(line).append("\n");
        }
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new Exception("Command failed with exit code " + exitCode + "\n" + sb.toString());
        }
        reader.close();
        if (!sb.isEmpty()) {
            System.out.println(sb.toString());
        }
        return sb.toString();

    }
}
